package cs236369.hw5;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Login
 * 
 * This servlet expects to get two parameters with names: username, password via the 
 * session variables
 */
@WebServlet({ "/Login", "/Login/*" })
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String userPage = "/index.jsp";	
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String pass = request.getParameter("password");
		HttpSession session = request.getSession();
		// if no user name or no password, return welcome page to client
		if(pass==null || username==null || pass.equals("") || username.equals("")) {
			session.setAttribute("message", "ERROR: Bad usrname or password");
			response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
			return;
		}
		
		// verify login details
		if(DBConnection.verifyLogin(username, pass)) {
			// verification succeed - create session and link the user to the session
			session.setAttribute("userName", username);
			User user;
			try {
				user = DBConnection.getUserDetails(username);
				session.setAttribute("name", user.getFirstName() + " " + user.getLastName());
				if(user.isAdmin()) {
					session.setAttribute("admin", "true");
				}
			} catch (RescueMeException e) { e.printStackTrace(); }
			//now redirect to MainUserPage
			response.sendRedirect(request.getContextPath() + userPage);
		} else { // verification failed- return welcome page
			session.setAttribute("message", "ERROR: Bad usrname or password");
			response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
